package org.itboys.mobile.controller.mobile;

import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.itboys.commons.CommonConstants;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dto.SundayFootprintDto;
import org.itboys.mobile.dto.SundayMemberDto;
import org.itboys.mobile.service.mongo.front.SundayFrontFootprintService;
import org.itboys.mobile.service.mongo.front.SundayFrontMemberService;
import org.itboys.mobile.util.AccountIdHoldUtils;
import org.itboys.mobile.util.MobileSignUtils;
import org.itboys.mobile.util.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhangyang on 2018/1/4.
 * 圣代_用户_controller_mobile
 */
@Controller
@RequestMapping("/sunday/mobile/member")
public class SundayMobileMemberController extends BaseController{

    @Autowired
    private SundayFrontMemberService memberService;
    @Autowired
    private SundayFrontFootprintService footprintService;

   @RequestMapping(value="/loginWithThird", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(value="【手机端】用户注册或登陆。使用第三方登陆：微信。")
    public void loginWithThird(HttpServletRequest request,
                              HttpServletResponse response,
                              @ApiParam(required=true, name="nickName", value="微信昵称")@RequestParam(value = "nickName", required = true)String nickName,
                              @ApiParam(required=true, name="image", value="微信头像")@RequestParam(value = "image", required = true)String image,
                              @ApiParam(required=true, name="unionId", value="微信UnionId")@RequestParam(value = "unionId", required = true)String unionId,
                              @ApiParam(required=true, name="openId", value="微信openId")@RequestParam(value = "openId", required = true)String openId,
                              @ApiParam(value = "随机数。【参与签名】")@RequestParam(value = "nonce", required = true) String nonce,
                              @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ){
        try{
            //2018年1月16日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
//                ResponseMessage.error(-1,"签名校验失败");
//                return;
            }
            SundayMemberDto member= memberService.loginWithThird(nickName,image, SundayCommonConstants.third_type_weixin,unionId,openId);
            ResponseMessage.success(member);
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer msgCode=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                msgCode=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/member/loginWithThird----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(msgCode,msg);
        }
    }
    @RequestMapping(value="/login", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(value="【手机端】用户注册或登陆。使用验证码。")
    public void login(HttpServletRequest request,
                      HttpServletResponse response,
                      @ApiParam(required=true, name="mobile", value="手机号。2018年4月18日启用")@RequestParam(value = "mobile", required = true)String mobile,
                      @ApiParam(required=true, name="code", value="验证码（发送类型：8验证码登录）。2018年4月18日启用")@RequestParam(value = "code", required = true)String code,
                      @ApiParam(value = "随机数。【参与签名】")@RequestParam(value = "nonce", required = true) String nonce,
                      @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ){
        try{
            //2018年1月16日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
//                ResponseMessage.error(-1,"签名校验失败");
//                return;
            }
            SundayMemberDto member= memberService.login(mobile,code);
            ResponseMessage.success(member);
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer msgCode=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                msgCode=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/member/login----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(msgCode,msg);
        }
    }
    /**
     * 退出登录。
     * @param request
     * @param response
     */
    @RequestMapping(value="/logout", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(value="【手机端】退出登录。")
    public void logout(HttpServletRequest request,
                       HttpServletResponse response,
                       @ApiParam(value = "随机数。【参与签名】")@RequestParam(value = "nonce", required = true) String nonce,
                       @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign){

        try{
            //2018年1月16日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
//                ResponseMessage.error(-1,"签名校验失败");
//                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
            memberService.logout(memberId);
            ResponseMessage.success();
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/member/logout----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
    /**
     * 退出登录。
     * @param request
     * @param response
     */
    @RequestMapping(value="/checkIsSign", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(value="【手机端】检查用户绑定微信（提现之前校验）直接返回：0否，1是。")
    public void checkIsSign(HttpServletRequest request,
                       HttpServletResponse response,
                       @ApiParam(value = "随机数。【参与签名】")@RequestParam(value = "nonce", required = true) String nonce,
                       @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign){

        try{
            //2018年1月16日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
//                ResponseMessage.error(-1,"签名校验失败");
//                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
           Integer result =  memberService.checkIsSign(memberId);
            ResponseMessage.success(result);
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/member/checkIsSign----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
    @RequestMapping(value="/resign", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(value="【手机端】用户绑定微信（提现之前先校验，再绑定）。")
    public void resign(HttpServletRequest request,
                      HttpServletResponse response,
                      @ApiParam(required=true, name="nickName", value="微信昵称")@RequestParam(value = "nickName", required = true)String nickName,
                      @ApiParam(required=true, name="image", value="微信头像")@RequestParam(value = "image", required = true)String image,
                      @ApiParam(required=true, name="unionId", value="微信UnionId")@RequestParam(value = "unionId", required = true)String unionId,
                      @ApiParam(required=true, name="openId", value="微信openId")@RequestParam(value = "openId", required = true)String openId,
                       @ApiParam(value = "随机数。【参与签名】")@RequestParam(value = "nonce", required = true) String nonce,
                      @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ){
        try{
            //2018年1月16日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
//                ResponseMessage.error(-1,"签名校验失败");
//                return;
            }
            Long memberId=AccountIdHoldUtils.getMemberId();
             memberService.resign(memberId,nickName,image,unionId,openId);
            ResponseMessage.success();
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer msgCode=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                msgCode=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/member/resign----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(msgCode,msg);
        }
    }
    /**
     * 修改个人信息。-1直接提示消息；
     * @param request
     * @param response
     * @param nickName
     * @param mobileName
     * @param address
     * @param email
     * @param image
     * @param idCard
     * @param desc
     */
    @RequestMapping(value="/update", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(value="【手机端】修改个人信息。")
    public void update(HttpServletRequest request,
                       HttpServletResponse response,
                       @ApiParam(required=false, name="nickName", value="昵称")@RequestParam(value = "nickName", required = false)String nickName,
                       @ApiParam(required=false, name="mobileName", value="联系电话")@RequestParam(value = "mobileName", required = false)String mobileName,
                       @ApiParam(required=false, name="address", value="地址")@RequestParam(value = "address", required = false)String address,
                       @ApiParam(required=false, name="email", value="电子邮箱")@RequestParam(value = "email", required = false)String email,
                       @ApiParam(required=false, name="image", value="头像")@RequestParam(value = "image", required = false)String image,
                       @ApiParam(required=false, name="idCard", value="身份证号码")@RequestParam(value = "idCard", required = false)String idCard,
                       @ApiParam(required=false, name="desc", value="个人简介")@RequestParam(value = "desc", required = false)String desc,
                       @ApiParam(required=false, name="birthDate", value="生日")@RequestParam(value = "birthDate", required = false)String birthDate,
                       @ApiParam(required=false, name="sex", value="性别。0女1男2保密")@RequestParam(value = "sex", required = false)Integer sex,
                       @ApiParam(value = "随机数。【参与签名】")@RequestParam(value = "nonce", required = true) String nonce,
                       @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign){

        try{
            //2018年1月16日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
//                ResponseMessage.error(-1,"签名校验失败");
//                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
            SundayMemberDto result =memberService.update( memberId, nickName, mobileName, address, email, image, idCard, desc,birthDate,sex);
            ResponseMessage.success(result);
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/member/update----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }


    @RequestMapping(value="/getDetail", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(value="【手机端】获取用户详情。含优惠券，关注等数量信息")
    public void getDetail(HttpServletRequest request,
                                  HttpServletResponse response,
                                  @ApiParam(value = "随机数。【参与签名】")@RequestParam(value = "nonce", required = true) String nonce,
                                  @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign){
        try{
            //2018年1月16日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
//                ResponseMessage.error(-1,"签名校验失败");
//                return;
            }
            SundayMemberDto member= memberService.packageDtoSingle( null, AccountIdHoldUtils.getMemberId(), false,true);
            ResponseMessage.success(member);
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code2=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code2=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/member/getDetail----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code2,msg);
        }
    }

    @RequestMapping(value="/getFootprint",method= { RequestMethod.POST,RequestMethod.GET})
    @ApiOperation(value="【手机端】获取足迹数据。")
    public void getFootprint(HttpServletRequest request,
                          HttpServletResponse response,
                          @ApiParam(required = true, name = "pageSize", value = "分页参数。每页数量。默认20") @RequestParam(value = "pageSize", required = true) String pageSize,
                          @ApiParam(required = true, name = "pageNumber", value = "分页参数。第几页。默认1") @RequestParam(value = "pageNumber", required = true) String pageNumber,
                          @ApiParam(required = false, name = "sort", value = "排序参数。字段名称。默认为空") @RequestParam(value = "sort", required = false) String sort,
                          @ApiParam(required = false, name = "order", value = "排序参数。。默认为空。ASC正序/DESC倒序") @RequestParam(value = "order", required = false) String order,
                          @ApiParam(value = "随机数。【参与签名】")@RequestParam(value = "nonce", required = true) String nonce,
                          @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign) {
        try{
            //2018年1月16日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
//                ResponseMessage.error(-1,"签名校验失败");
//                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
            List<SundayFootprintDto> list = footprintService.select(memberId,request);
            ResponseMessage.success(list);
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/member/getFootprint----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
    /**
     * 分享页
     * @param model
     * @return
     */
    @RequestMapping(value="/share", method= {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value="【手机端】获取微信分享页。h5页面")
    public String share(Model model,
                        @ApiParam(required = true, value = "用户id")@RequestParam(value = "memberId", required = true)Long memberId) {
        try {
            //SundayMemberSessionDto member=
            model.addAttribute("memberDto", memberService.share(memberId));
            return "/aigou/mobile/member/share";
        } catch (Exception e) {
            logger.error("/sunday/mobile/member/share----e=" + e.getMessage());
            e.printStackTrace();
            return "/aigou/weixin/error";
        }
    }



    @RequestMapping(value="/getLeaguer",method= { RequestMethod.POST,RequestMethod.GET})
    @ApiOperation(value="【手机端】获取我的会员数据。不分页，含统计会员的总数")
    public void getLeaguer(HttpServletRequest request,
                             HttpServletResponse response,
                            /* @ApiParam(required = true, name = "type", value = "类型:1-获取一级会员,2-获取二级会员。【参与签名】")@RequestParam(value = "type", required = true)Integer type,
                             @ApiParam(required = true, name = "pageSize", value = "分页参数。每页数量。默认20") @RequestParam(value = "pageSize", required = true) String pageSize,
                             @ApiParam(required = true, name = "pageNumber", value = "分页参数。第几页。默认1") @RequestParam(value = "pageNumber", required = true) String pageNumber,
                             @ApiParam(required = false, name = "sort", value = "排序参数。字段名称。默认为空") @RequestParam(value = "sort", required = false) String sort,
                             @ApiParam(required = false, name = "order", value = "排序参数。。默认为空。ASC正序/DESC倒序") @RequestParam(value = "order", required = false) String order,
                             */@ApiParam(value = "随机数。【参与签名】")@RequestParam(value = "nonce", required = true) String nonce,
                             @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign) {
        try{
            //2018年1月16日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("nonce", nonce);
            param.put("sign", sign);
           // param.put("type",type);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
//                ResponseMessage.error(-1,"签名校验失败");
//                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
           /* List<SundayMemberDto> list = memberService.getLeaguerData(request,memberId,type);*/
            Map<String,Object> result = memberService.getLeaguer(memberId);
            ResponseMessage.success(result);
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/member/getLeaguer----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
    @ApiOperation(value="【手机端】客服页面（暂时静态页面）")
    @RequestMapping(value="/chat", method= {RequestMethod.GET,RequestMethod.POST})
    public String chat(
            HttpServletRequest request,
            Model model){
        try{
            //Long memberId = AccountIdHoldUtils.getSessionMember(request).getId();
            //SundayMemberDto member = memberService.packageDtoSingle(null,memberId,true,true);
            //  model.addAttribute("memberDto",member);
            return "/aigou/mobile/member/chat";

        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code= CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code= CommonConstants.TOKEN_CODE;
                msg= CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/weixin/member/chat----e="+e.getMessage());
            }
            e.printStackTrace();
            return "/aigou/weixin/error";
        }
    }
}
